// pages/placeOrder/placeOrder.js
// import Toast from '@vant/weapp/dist/toast/toast';
import { clearShop} from '../../http/api model/shopCar'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    youhuijuan:0,
    shopList:[],
    show: false,
    selectTime:'立即取餐',
    columns: [
      { text: '立即取餐' }
    ],
    checkedJuan:"",
    loading:true,
    order:{
      // 商店id
      shopid:'',
      foodlist:[],
      userid:'',
      status:1,
      totalprice:'',
      total:'',
      remarks:'',
      taketime:'立即取餐'
    }
  },
  onChange(event) {
    const { picker, value, index } = event.detail;

    this.setData({
      ['order.taketime']:this.data.columns[index].text,
      selectTime:this.data.columns[index].text
    })
  },
  onSubmit(){
    Dialog.confirm({
      title: '确定支付吗？',
      message: '',
    })
      .then(() => {

        wx.showLoading({
          title:"支付中"
        })
        const {shopList,order,checkedJuan} = this.data;
        wx.request({
          url: 'http://localhost:5555/users/addUserOrder',
          method:'post',
          data:{
            userid:wx.getStorageSync('openID'),
            shopid:shopList.id,
            status:0,
            msg:order.remarks,
            discount:checkedJuan,
            tackTime:order.taketime,
            sumPrice:shopList.selectShopCar.reduce((sum,n)=>sum+n.num*n.price,0),
            sumCount:shopList.selectShopCar.reduce((sum,n)=>sum+n.num,0),
            selectShopCar:shopList.selectShopCar
          },
          success:(res)=>{
            // 扣优惠券
            clearShop({
              shopid:this.data.order.shopid || '',
              userid:wx.getStorageSync('openID')
            })
            if(this.data.checkedJuan){
              wx.request({
                url: 'http://localhost:5555/users/ChangeUserCoupon',
                data:this.data.checkedJuan,
                success(){
                  // wx.showToast({
                  //   title: '优惠券扣除成功！',
                  //   icon: 'success',
                  //   duration: 1000 //持续的时间
                  // })
          
                }
              })
            }
            wx.hideLoading()
            wx.showToast({
              title: '支付成功！',
              icon: 'success',
              duration: 2500 //持续的时间
            })
            let shopcar = wx.getStorageSync('shopCar');
            delete shopcar[this.data.order.shopid];
            wx.setStorageSync('shopCar',shopcar)
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/shopCar/shopCar?active=1',
              })
            }, 1000);
          },
          fail(err){
            console.log("订单提交失败",err);
          }
        })
      })
      .catch(() => {
        // on cancel
      }).finally(()=>{

      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getJUAN()
    this.getCouPonData()
    this.setData({
      ['order.shopid']:options.shopId
    })
    // 加载取餐时间数据
    this.loadTakeTime()
    const shops = wx.getStorageSync('shopCar');
    for(let key in shops){
      for(let i=0;i<shops[key].length;i++){
        if(shops[key][i].num==0){
          shops[key].splice(i,1);
          i--;
        }
      }
    }
wx.setStorageSync('shopCar', shops)
    this.setData({
      shopList:wx.getStorageSync('shopCarINFO')
    })
    this.loadOrderData()
  },
  getJUAN(){
    const checkedJuan = wx.getStorageSync('checkedJuan');
    this.setData({
      checkedJuan
    })
  },
  showPopup() {
    this.setData({ show: true });
  },
onShow(){
  this.getJUAN()
  this.getCouPonData()
  this.loadOrderData()
},
  onClose() {
    this.setData({ show: false });
  },
  goCoupon(){
    wx.navigateTo({
      url: `/pages/useCoupon/useCoupon?shopId=${this.data.order.shopid}`
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  inputFrame(e) {
    this.setData({
      ['order.remarks']:e.detail
    })
  },
  loadOrderData(){
    // 获取用户openid
    let id = wx.getStorageSync('openID');
    // 获取商品列表
    let foodlist = this.data.shopList;
    // 获取商品总数
    // let total = foodlist.reduce((t,i)=>{
    //   return t+i.num;
    // },0)
    // 获取商品总价
    // let totalprice = foodlist.reduce((t,i)=>{
    //   return t+i.num*i.price;
    // },0)
    // let arr = foodlist.map(i=>{
    //   return {
    //     shopid:i.shopid,
    //     _id:i._id
    //   }
    // })
    this.setData({
      ['order.userid']:id,
    })
  },
  onReady() {

  },

loadTakeTime(){
  let mycolums
    for(let i=1;i<6;i++){
      let time = new Date(new Date().getTime()+(40*60*1000)*i);
      mycolums = this.data.columns;
      let shi = time.getHours()>=10?time.getHours():`0${time.getHours()}`;
      let fen = time.getMinutes()>=10?time.getMinutes():`0${time.getMinutes()}`;
      mycolums.push({text:`${shi}:${fen}`})
    }
    this.setData({
      columns:mycolums
    })
},
getCouPonData(){
  const userid = wx.getStorageSync('openID');
  wx.request({
    url: 'http://localhost:5555/users/getUserCoupon',
    method:"get",
    data:{
      userid
    },
    success:(res)=>{
      const data = res.data;
      const count = data.reduce((sum,item)=>{
        return sum+item.num
      },0)
      this.setData({
        youhuijuan:count,
        loading:false
      })
    }
  })
}
,onUnload(){
  wx.setStorageSync('checkedJuan','')
}
})